package com.liu.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;


@RestController
@RequestMapping("/upload")
@CrossOrigin
public class UploadController {

    @Value("${vue-imagePath}")
    private String UPLOAD_FOLDER;

    @Resource
    private ResourceLoader resourceLoader;

    @PostMapping("/image")
    public Object image(MultipartFile file) {

        if (Objects.isNull(file) || file.isEmpty()) {
            return "文件为空，请重新上传";
        }

        try {
            byte[] bytes = file.getBytes();
            String imageName = UUID.randomUUID().toString() + file.getOriginalFilename();
            Path path = Paths.get(UPLOAD_FOLDER + imageName);
            //如果没有files文件夹，则创建
            if (!Files.isWritable(path)) {
                Files.createDirectories(Paths.get(UPLOAD_FOLDER));
            }
            //文件写入指定路径
            Files.write(path, bytes);
            Map<String, String> map = new HashMap<String, String>();
            map.put("userId",imageName );
            map.put("id",imageName );
            map.put("title",imageName );
            map.put("body",imageName );
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            return "后端异常...";
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = "/{filename:.+}")
    @ResponseBody
    public ResponseEntity<?> getFile(@PathVariable String filename) {
        try {
            System.out.print(filename);
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(UPLOAD_FOLDER, filename).toString()));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
}